﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using GRWL.BZSC.UI.CustomCtrl;

namespace GRWL.BZSC.UI
{
    public partial class PickingLxFrm : BaseFrm
    {
        //BaseFrm中已有声明
        //public CodeRuleFrm.CodeRule codeRule { get; set; }

        // 单据编辑状态
        //public GRWL.BZSC.UI.Common.BillOperateType EditStatus;

        private bool bGraph = false;
        private void bindDepot()
        {
            TB_Depot[] tbDepot = this.BaseDataProxy.FindDepots(null, null, null);
            DataTable dtDepot = tbDepot.ToDataTable();

            this.t_depot.Items.Add("[]");
            for (int i = 0; i < dtDepot.Rows.Count; i++)
            {
                this.t_depot.Items.Add(dtDepot.Rows[i]["name"] + "[" + dtDepot.Rows[i]["id"] + "]");
            }
            //this.t_depot.DataSource = dtDepot;
            //this.t_depot.ValueMember = "id";
            //this.t_depot.DisplayMember = "name";
        }

        public PickingLxFrm()
        {
            InitializeComponent();

            this.BaseDataProxy = new BaseDataClient();
            this.BaseDataProxy.Open();

            this.codeRule = new CodeRuleFrm.CodeRule();

            EditStatus = Common.BillOperateType.None;

            SetControlsStatus(false);
            dtpData.SetDataGridViewNum(true);
            dtpData.SetDataGridViewNumName("序号");
        }

        private void SetControlsStatus(bool SetEnagledFlag)
        {
            //this.txtDjh.Enabled = SetEnagledFlag;
            dtpOutDate.Enabled = SetEnagledFlag;
            //cbType.Enabled = SetEnagledFlag;
            txtDepartment.Enabled = SetEnagledFlag;
            txtBusinessman.Enabled = SetEnagledFlag;
            txtMemo.Enabled = SetEnagledFlag;

            btnSave.Enabled = SetEnagledFlag;
            btnFromSc.Enabled = SetEnagledFlag;
            btnSelect.Enabled = SetEnagledFlag;
            btnDelete.Enabled = SetEnagledFlag;
            btnDelItem.Enabled = SetEnagledFlag;
            btnConfirm.Enabled = SetEnagledFlag;
            btnPrint.Enabled = SetEnagledFlag;

            dtpData.ReadOnly = !SetEnagledFlag;
            setReadOnly(SetEnagledFlag);
        }

        private void setReadOnly(bool b)
        {
            for (int i = 0; i < this.dtpData.Columns.Count; i++)
            {
                if ( b && (this.dtpData.Columns[i].Name == "t_num" || this.dtpData.Columns[i].Name == "t_depot" || this.dtpData.Columns[i].Name == "t_memo"))
                {
                    this.dtpData.Columns[i].ReadOnly = false;
                }
                else
                {
                    this.dtpData.Columns[i].ReadOnly = true;
                }
            }
        }

        private void PickingLxFrm_Load(object sender, EventArgs e)
        {
            SetControlsStatus(false);
            bindDepot();

            GRWL.BZSC.Common.EventCommon.SelectMaterialSpec += new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(addmaterial);

            GRWL.BZSC.Common.EventCommon.FindMaterialUdDGVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(updateFindMaterial);
            //GRWL.BZSC.Common.EventCommon.FindMaterialUdDGVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(btnSelect_Click);
            //setReadOnly();
        }

        private void addmaterial(object o, EventArgs arg)
        {

            //DataTable dt = new DataTable();
            //dt.Columns.Add("material");
            //dt.Columns.Add("materialCode");
            //dt.Columns.Add("materialName");
            //dt.Columns.Add("specs");
            //dt.Columns.Add("batchNo");//批号
            //dt.Columns.Add("depot");//仓库id
            //dt.Columns.Add("depotName");//仓库名称
            //dt.Columns.Add("num");
            //dt.Columns.Add("unit");
            //dt.Columns.Add("scd");
            //dt.Columns.Add("gx");

            if (arg != null)
            {
                bGraph = true;
                CommonEventArg<DataTable> argObj = (CommonEventArg<DataTable>)arg;

                for (int i = 0; i < argObj.t.Rows.Count; i++)
                {

                    int j = dtpData.Rows.Add();
                    //this.dtpData.Rows[j].Cells["id4"].Value = argObj.t.Rows[i]["material"];// argObj.t.RecvDetail.id;// tD[i].RecvDetail.id;
                    this.dtpData.Rows[j].Cells["id2"].Value = argObj.t.Rows[i]["material"];
                    this.dtpData.Rows[j].Cells["t_material"].Value = argObj.t.Rows[i]["materialCode"];// argObj.t.RecvDetail.materialCode;
                    this.dtpData.Rows[j].Cells["t_cnName"].Value = argObj.t.Rows[i]["materialName"];//argObj.t.MaterialName;
                    this.dtpData.Rows[j].Cells["t_specs"].Value = argObj.t.Rows[i]["specs"];//argObj.t.RecvDetail.specs;
                    this.dtpData.Rows[j].Cells["t_unit"].Value = argObj.t.Rows[i]["unit"];//argObj.t.Unit;
                    this.dtpData.Rows[j].Cells["t_num"].Value = argObj.t.Rows[i]["num"];//argObj.t.RecvDetail.num;
                    this.dtpData.Rows[j].Cells["id3"].Value = argObj.t.Rows[i]["depot"];//argObj.t.RecvDetail.depot;
                    this.dtpData.Rows[j].Cells["t_depot"].Value = argObj.t.Rows[i]["depotName"] + "[" + argObj.t.Rows[i]["depot"] + "]";//argObj.t.DepotName + "[" + argObj.t.RecvDetail.depot + "]";
                    this.dtpData.Rows[j].Cells["t_batchNo"].Value = argObj.t.Rows[i]["batchNo"];//argObj.t.RecvDetail.batchNo;
                    this.dtpData.Rows[j].Cells["t_prdnId"].Value = argObj.t.Rows[i]["scdid"];//argObj.t.RecvDetail.batchNo;
                    this.dtpData.Rows[j].Cells["t_prdnCode"].Value = argObj.t.Rows[i]["scd"];//argObj.t.RecvDetail.requirement;
                    this.dtpData.Rows[j].Cells["t_workstageid"].Value = argObj.t.Rows[i]["gxid"];//argObj.t.RecvDetail.workstage;
                    this.dtpData.Rows[j].Cells["t_workstage"].Value = argObj.t.Rows[i]["gx"];//argObj.t.RecvDetail.workstage;
                    this.dtpData.Rows[j].Cells["t_prdnMaterialId"].Value = argObj.t.Rows[i]["prdnMaterialId"];//生产材料id
                    //this.dtpData.Rows[j].Cells["t_memo"].Value = argObj.t.Rows[i]["specs"];//argObj.t.RecvDetail.memo;
 
                }
                bGraph = false;

                #region
                //if (argObj != null)
                //{
                //    //for (int i = 0; i < argObj.Count(); i++)
                //    //{

                //        int j = dtpData.Rows.Add();
                //        this.dtpData.Rows[j].Cells["id4"].Value = argObj.t.RecvDetail.id;// tD[i].RecvDetail.id;
                //        this.dtpData.Rows[j].Cells["id2"].Value = argObj.t.RecvDetail.material;
                //        this.dtpData.Rows[j].Cells["t_material"].Value = argObj.t.RecvDetail.materialCode;
                //        this.dtpData.Rows[j].Cells["t_cnName"].Value = argObj.t.MaterialName;
                //        this.dtpData.Rows[j].Cells["t_specs"].Value = argObj.t.RecvDetail.specs;
                //        this.dtpData.Rows[j].Cells["t_unit"].Value = argObj.t.Unit;
                //        this.dtpData.Rows[j].Cells["t_num"].Value = argObj.t.RecvDetail.num;
                //        this.dtpData.Rows[j].Cells["id3"].Value = argObj.t.RecvDetail.depot;
                //        this.dtpData.Rows[j].Cells["t_depot"].Value = argObj.t.DepotName + "[" + argObj.t.RecvDetail.depot + "]";
                //        this.dtpData.Rows[j].Cells["t_batchNo"].Value = argObj.t.RecvDetail.batchNo;
                //        this.dtpData.Rows[j].Cells["t_requirement"].Value = argObj.t.RecvDetail.requirement;
                //        this.dtpData.Rows[j].Cells["t_workstage"].Value = argObj.t.RecvDetail.workstage;
                //        this.dtpData.Rows[j].Cells["t_memo"].Value = argObj.t.RecvDetail.memo;
                //        //this.dtpData.Rows[j].Cells["id4"].Value = tD[i].RecvDetail.id;

                //}
                #endregion
            }
        }

        private void updateFindMaterial(object o, EventArgs arg)
        {
            CommonEventArg<QMaterial[]> argObj = (CommonEventArg<QMaterial[]>)arg;
            if (argObj != null)
            {
                foreach (QMaterial m in argObj.t)
                {
                    //decimal? currentStock = this.BaseDataProxy.GetCurrentStock(m.Id);
                    //XMaterial xm = this.BaseDataProxy.GetXMaterial(m.Id, null);
                    //if (xm != null)
                    //{

                        //    if (frm.SelectorItem != null)
                        //    {
                        int i = dtpData.Rows.Add();
                        //QMaterial qm = frm.SelectorItem;
                        dtpData.Rows[i].Cells["id2"].Value =m.Id;// xm.M qm.Id;
                        dtpData.Rows[i].Cells["t_material"].Value = m.Code;// qm.Code;
                        dtpData.Rows[i].Cells["t_cnname"].Value = m.CnName;// qm.CnName;
                        dtpData.Rows[i].Cells["t_Specs"].Value = m.Specs;// qm.Specs;
                        dtpData.Rows[i].Cells["t_unit"].Value = m.Unit;// qm.Unit;
                        dtpData.Rows[i].Cells["t_BatchNo"].Value = m.BatchNo;// qm.BatchNo;
                        //        //dtpData.Rows[i].Cells[""].Value = frm.SelectorItem.Key;
                        //        //dtpData.Rows[i].Cells[""].Value = frm.SelectorItem.Key;
                        //    }

                        //this.dataGridView1.Rows.Add(new object[] {null, 1,null,null,null,m.Id,m.Code,m.CnName,m.Specs,
                        //m.PrjtId,m.PrjtCode,null,1,1,DateTime.Now.ToShortDateString(),DateTime.Now.ToShortDateString(),
                        //m.Source,xm.Material.department,xm.DepartmentName,currentStock,currentStock,currentStock,1,1,
                        //xm.CategoryName,xm.Material.unit,xm.Material.isNominal,
                        //this.txtBoxCode.Text,this._Id,false,false,1});
                    //}
                }
            }
        }

        private void SetNull()
        {
            this.txtDjh.Text = "";
            this.txtOperator.Text = "";
            this.txtAccessor.Text = "";
            this.txtStatus.Text = "";
            this.cbType.Text = "";
            this.txtDepartment.SetSelected(null);
            this.txtBusinessman.SetSelected(null);
            this.txtMemo.Text = "";
            this.txtMender.Text = "";

            for (int i = dtpData.Rows.Count - 2; i >= 0; i--)
            {
                dtpData.Rows.RemoveAt(i);
            }
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            //放弃新单
            if (EditStatus == Common.BillOperateType.Add)
            {
                EditStatus = Common.BillOperateType.None;
                SetControlsStatus(false);

                dtpData.CancelEdit();
                SetNull();
                return;
            }

            //新单输入

            SetControlsStatus(true);
            SetNull();
            EditStatus = Common.BillOperateType.Add;
            this.btnConfirm.Enabled = false;
            //this.txtDjh.Text = BaseDataProxy.GetSerialNo(1, "LL", 4, true,true, true);
            this.txtOperator.Text = SysLoginUserInfo.UserName;
            this.txtStatus.Text = "未批";

            tMain.Clear();
            DataRow NewMainRow = tMain.NewRow();
            //NewMainRow["code"] = this.txtDjh.Text;
            NewMainRow["recvDate"] = this.dtpOutDate.Value;
            NewMainRow["status"] = this.txtStatus.Text;

            tMain.Rows.Add(NewMainRow);
        }

        private void txtDepartment_SelectorClick(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            DeptFrm frm = new DeptFrm();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txtDepartment.ValueType = Selector.NodeValueType.Name;
                txtDepartment.SetSelected(frm.SelectorItem);

                tMain.Rows[0]["department"] = Common.StringToInt(frm.SelectorItem.Key);
            }
        }

        private void traderSelector_SelectorClick(object sender, EventArgs e)
        {
            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
            {
                return;
            }

            UserFrm frm = new UserFrm();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                txtBusinessman.ValueType = Selector.NodeValueType.Name;
                txtBusinessman.SetSelected(frm.SelectorItem);

                tMain.Rows[0]["businessman"] = Common.StringToInt(frm.SelectorItem.Value);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            this.toolStrip1.Focus();//.dtpData.Focus();
            if (cbType.Text == "")
            {
                MessageBox.Show("请输入领料类型");
                return;
            }

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update) & (EditStatus == Common.BillOperateType.Delete))
                return;

            if (EditStatus == Common.BillOperateType.Add)
            {
                if (string.IsNullOrEmpty(tMain.Rows[0]["code"].ToString()))
                {
                    this.txtDjh.Text = BaseDataProxy.GetSerialNo(1, "LL", 4, true, true, true);
                    tMain.Rows[0]["code"] = this.txtDjh.Text;
                }
                tMain.Rows[0]["operator"] = SysLoginUserInfo.UserId;
                tMain.Rows[0]["createTime"] = DateTime.Now;
            }
            else
            {
                tMain.Rows[0]["mender"] = SysLoginUserInfo.UserId;
                this.txtMender.Text = SysLoginUserInfo.UserName;
                tMain.Rows[0]["updateTime"] = DateTime.Now;
            }
            tMain.Rows[0]["memo"] = this.txtMemo.Text;

            tMain.AcceptChanges();
            tDetail.AcceptChanges();

            //将 DataTable 转换为写入后台格式 TB_xxxxx

            TB_RecvMaterial tbRecvMaterial = OTConverter.ConvertToObject<TB_RecvMaterial>(tMain.Rows[0]);

            if (EditStatus == Common.BillOperateType.Add)
            {
                //tMain.AcceptChanges();
                //int NewBillId = BaseDataProxy.AddRecvMaterial(tbRecvMaterial);

                tDetail.Clear();

                for (int i = 0; i < this.dtpData.Rows.Count - 1; i++)
                {
                    if (dtpData.RCText(i, "t_num").ToString() == "" || dtpData.RCText(i, "t_depot").ToString() == "")
                    {
                        MessageBox.Show("数量，领料仓库不能为空！(^_^)");
                        return;
                    }
                    DataRow NewDetailRow = tDetail.NewRow();

                    //NewDetailRow["id"] = NewBillId;
                    //NewDetailRow["recvMaterial"] = NewBillId;
                    NewDetailRow["recvMtrlCode"] = this.txtDjh.Text;// this.dtpData.RCText(i, "");
                    NewDetailRow["material"] = Convert.ToInt32(this.dtpData.RCText(i, "id2"));
                    NewDetailRow["materialCode"] = this.dtpData.RCText(i, "t_material");
                    NewDetailRow["batchNo"] = this.dtpData.RCText(i, "t_batchNo");
                    if (dtpData.RCText(i, "t_num") != "")
                        NewDetailRow["num"] = Convert.ToDecimal(dtpData.RCText(i, "t_num"));
                    if (this.dtpData.RCText(i, "id3").ToString() != "")
                        NewDetailRow["depot"] = Convert.ToInt32(this.dtpData.RCText(i, "id3"));

                    //if (this.dtpData.RCText(i, "t_depot").ToString() != "")
                    //    NewDetailRow["depot"] = Convert.ToInt32(this.dtpData.RCText(i, "t_depot"));
                    //NewDetailRow["requirement"] = this.dtpData.RCText(i, "");
                    //NewDetailRow["rqrtCode"] = this.dtpData.RCText(i, "");
                    NewDetailRow["memo"] = this.dtpData.RCText(i, "t_memo");
                    NewDetailRow["specs"] = this.dtpData.RCText(i, "t_specs");
                    //NewDetailRow["order"] = this.dtpData.RCText(i, "");
                    //NewDetailRow["oederCode"] = this.dtpData.RCText(i, "");
                    //NewDetailRow["price"] = this.dtpData.RCText(i, "");
                    //NewDetailRow["amount"] = this.dtpData.RCText(i, "");
                    if (this.dtpData.RCText(i, "t_prdnId") != "")
                        NewDetailRow["prdnId"] = Convert.ToInt32(this.dtpData.RCText(i, "t_prdnId"));
                    NewDetailRow["prdnCode"] = this.dtpData.RCText(i, "t_prdnCode");
                    if (this.dtpData.RCText(i, "t_workstageid") != "")
                        NewDetailRow["workstage"] = Convert.ToInt32(this.dtpData.RCText(i, "t_workstageid"));
                    if (this.dtpData.RCText(i, "t_prdnMaterialId") != "")
                        NewDetailRow["prdnMaterialId"] = Convert.ToInt32(this.dtpData.RCText(i, "t_prdnMaterialId"));
                    tDetail.Rows.Add(NewDetailRow);
                }

                List<TB_RecvDetail> lsRecvDetail = OTConverter.ConvertTableToObject<TB_RecvDetail>(tDetail);
                TB_RecvDetail[] tbRecvDetail = lsRecvDetail.ToArray();

                tDetail.AcceptChanges();

                //int a = 0;
                tbRecvMaterial.TB_RecvDetail = tbRecvDetail;
                int id = BaseDataProxy.AddRecvMaterial(tbRecvMaterial);
                tMain.Rows[0]["id"] = id;
                EditStatus = Common.BillOperateType.Update;
                this.btnConfirm.Enabled = true;
                MessageBox.Show("已成功保存单据.");
                
            }
            else if (EditStatus == Common.BillOperateType.Update)
            {

                tDetail.Clear();
                for (int i = 0; i < this.dtpData.Rows.Count - 1; i++)
                {
                    if (dtpData.RCText(i, "t_num").ToString() == "" || dtpData.RCText(i, "t_depot").ToString() == "")
                    {
                        MessageBox.Show("数量，领料仓库不能为空！(^_^)");
                        return;
                    }
                    DataRow NewDetailRow = tDetail.NewRow();
                    //if (this.dtpData.RCText(i, "id4") != "")
                    //    NewDetailRow["id"] = Convert.ToInt32(this.dtpData.RCText(i, "id4"));
                    NewDetailRow["recvMaterial"] = Convert.ToInt32(tMain.Rows[0]["id"]);
                    NewDetailRow["recvMtrlCode"] = this.txtDjh.Text;
                    NewDetailRow["material"] = Convert.ToInt32(this.dtpData.RCText(i, "id2"));
                    NewDetailRow["materialCode"] = this.dtpData.RCText(i, "t_material");
                    NewDetailRow["specs"] = this.dtpData.RCText(i, "t_specs");
                    NewDetailRow["batchNo"] = this.dtpData.RCText(i, "t_batchNo");
                    if (dtpData.RCText(i, "t_num") != "")
                        NewDetailRow["num"] = Convert.ToDecimal(dtpData.RCText(i, "t_num"));
                    if (this.dtpData.RCText(i, "id3").ToString() != "")
                        NewDetailRow["depot"] = Convert.ToInt32(this.dtpData.RCText(i, "id3"));
                    if (this.dtpData.RCText(i, "t_prdnId") != "")
                        NewDetailRow["prdnId"] = Convert.ToInt32(this.dtpData.RCText(i, "t_prdnId"));
                    NewDetailRow["prdnCode"] = this.dtpData.RCText(i, "t_prdnCode");
                    if (this.dtpData.RCText(i, "t_workstageid") != "")
                        NewDetailRow["workstage"] = Convert.ToInt32(this.dtpData.RCText(i, "t_workstageid"));
                    NewDetailRow["memo"] = this.dtpData.RCText(i, "t_memo");

                    tDetail.Rows.Add(NewDetailRow);
                }

                List<TB_RecvDetail> lsRecvDetail = OTConverter.ConvertTableToObject<TB_RecvDetail>(tDetail);
                TB_RecvDetail[] tbRecvDetail = lsRecvDetail.ToArray();

                tDetail.AcceptChanges();

                tbRecvMaterial.TB_RecvDetail = tbRecvDetail;

                BaseDataProxy.UpdateRecvMaterial(tbRecvMaterial, true);
                MessageBox.Show("已成功保存单据.");
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            this.cbType.Text = "零星领料";
            FindMaterialFrm frm = new FindMaterialFrm();
            frm.MutiSelect = true;
            frm.StockNullable = true;
            frm.ShowDialog(this);
            this.btnFromSc.Enabled = false;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            //加载打开单据
            FindBillFrm frm = new FindBillFrm();
            frm.AllowMulitSelect = false;
            frm.SelectBillType = GRWL.BZSC.Common.EnumCommon.BillType.LL;
            frm.ShowDialog();
            if (frm.DialogResult == DialogResult.OK)
            {
                if (frm.SelectedItems != null)
                {
                    bGraph = true;
                    for (int i = dtpData.Rows.Count - 2; i >= 0; i--)
                    {
                        dtpData.Rows.RemoveAt(i);
                    }
                    QRecvMaterial qrecv = OTConverter.ConvertToObject<QRecvMaterial>(frm.SelectedItems);
                    OpenBill(qrecv.Id);
                    EditStatus = Common.BillOperateType.Update;
                    bGraph = false;
                }
            }

            //SelectBillFrm frm = new SelectBillFrm();
            //frm.SetCondition(GRWL.BZSC.Common.EnumCommon.BillType.LL, BillPrefix, false);
            //frm.ShowDialog();
            //if (frm.SelectBills.Count > 0)
            //{
            //    bGraph = true;

            //    //for (int i = 0; i < dtpData.Rows.Count; i++)
            //    for (int i = dtpData.Rows.Count - 2; i >= 0; i--)
            //    {
            //        dtpData.Rows.RemoveAt(i);
            //    }
            //    OpenBill(frm.SelectBills[0].BillId);
            //    //MessageBox.Show(frm.SelectBills[0].BillId.ToString()); 
            //    EditStatus = Common.BillOperateType.Update;

            //    bGraph = false;
            //}

            if (cbType.Text == "零星领料")
                this.btnFromSc.Enabled = false;
            else if (cbType.Text == "生产领料")
                this.btnSelect.Enabled = false;
        }

        private void OpenBill(int BillId)
        {
            XRecvMaterial tM = BaseDataProxy.GetXRecvMaterial(BillId);
            XRecvDetail[] tD = BaseDataProxy.GetRecvDetails(BillId);

            #region
            if (tM != null)
            {

                tMain.Clear();
                DataRow NewMainRow = tMain.NewRow();
                NewMainRow["id"] = tM.RecvMaterial.id;

                this.txtDjh.Text = tM.RecvMaterial.code;
                NewMainRow["code"] = this.txtDjh.Text;

                if (tM.RecvMaterial.recvDate != null)
                {
                    this.dtpOutDate.Value = Convert.ToDateTime(tM.RecvMaterial.recvDate);
                    NewMainRow["recvDate"] = this.dtpOutDate.Value;
                }

                if (tM.RecvMaterial.department != null)
                {
                    SelectItem item = new SelectItem();
                    item.Name = tM.DepartmentName;
                    item.Key = tM.DepartmentCode;
                    item.Value = tM.RecvMaterial.department.ToString();
                    this.txtDepartment.SetSelected(item);

                    NewMainRow["department"] = tM.RecvMaterial.department;
                }

                if (tM.RecvMaterial.businessman != null)
                {
                    SelectItem item = new SelectItem();
                    item.Name = tM.BusinessName;
                    item.Key = tM.BusinessCode;
                    item.Value = tM.RecvMaterial.businessman.ToString();
                    this.txtBusinessman.SetSelected(item);

                    NewMainRow["businessman"] = tM.RecvMaterial.businessman;
                }

                if (tM.RecvMaterial.@operator != null)
                {
                    this.txtOperator.Text = tM.OperatorName;
                    NewMainRow["operator"] = tM.RecvMaterial.@operator;
                }

                this.txtMender.Text = tM.MenderName;//修改人
                NewMainRow["mender"] = SysLoginUserInfo.UserId;

                this.txtMemo.Text = tM.RecvMaterial.memo;
                NewMainRow["memo"] = tM.RecvMaterial.memo;

                this.txtStatus.Text = tM.RecvMaterial.status;
                NewMainRow["status"] = this.txtStatus.Text;

                this.cbType.Text = tM.RecvMaterial.type;
                NewMainRow["type"] = this.cbType.Text;

                if (tM.RecvMaterial.updateTime != null)
                    this.dtpUpdatetime.Value = Convert.ToDateTime(tM.RecvMaterial.updateTime);
                if (tM.RecvMaterial.verifyTime != null)
                    this.dtpvertime.Value = Convert.ToDateTime(tM.RecvMaterial.verifyTime);
                this.txtAccessor.Text = tM.AssessorName;

                tMain.Rows.Add(NewMainRow);
            }
            #endregion

            #region 
            if (tD != null)
            {
                for (int i = 0; i < tD.Count(); i++)
                {

                    int j = dtpData.Rows.Add();
                    this.dtpData.Rows[j].Cells["id4"].Value = tD[i].RecvDetail.id;
                    this.dtpData.Rows[j].Cells["id2"].Value = tD[i].RecvDetail.material;
                    this.dtpData.Rows[j].Cells["t_material"].Value = tD[i].RecvDetail.materialCode;
                    this.dtpData.Rows[j].Cells["t_cnName"].Value = tD[i].MaterialName;
                    this.dtpData.Rows[j].Cells["t_specs"].Value = tD[i].RecvDetail.specs;
                    this.dtpData.Rows[j].Cells["t_unit"].Value = tD[i].Unit;
                    this.dtpData.Rows[j].Cells["t_num"].Value = tD[i].RecvDetail.num;
                    this.dtpData.Rows[j].Cells["id3"].Value = tD[i].RecvDetail.depot;
                    this.dtpData.Rows[j].Cells["t_depot"].Value = tD[i].DepotName + "[" + tD[i].RecvDetail.depot + "]";
                    this.dtpData.Rows[j].Cells["t_batchNo"].Value = tD[i].RecvDetail.batchNo;
                    this.dtpData.Rows[j].Cells["t_prdnId"].Value = tD[i].RecvDetail.prdnId;//生产单id
                    this.dtpData.Rows[j].Cells["t_prdnCode"].Value = tD[i].RecvDetail.prdnCode;//生产单号
                    this.dtpData.Rows[j].Cells["t_workstageid"].Value = tD[i].RecvDetail.workstage;//生产工序id
                    this.dtpData.Rows[j].Cells["t_workstage"].Value = tD[i].RecvDetail.workstage;//生产工序
                    this.dtpData.Rows[j].Cells["t_memo"].Value = tD[i].RecvDetail.memo;
                    this.dtpData.Rows[j].Cells["t_prdnMaterialId"].Value = tD[i].RecvDetail.prdnMaterialId;
                    //this.dtpData.Rows[j].Cells["id4"].Value = tD[i].RecvDetail.id;
                }

                //dtpData.DataSource = dt;//不用datasource绑定，否则无法再添加
            }
            #endregion

            if (this.txtStatus.Text.ToString() == "已批")
            {
                //审批后,不允许再修改
                EditStatus = Common.BillOperateType.View;
                SetControlsStatus(false);
            }
            else if (this.txtStatus.Text.ToString() == "未批")
            {
                //未审批,允许再修改
                EditStatus = Common.BillOperateType.Update;
                SetControlsStatus(true);
            }
        }

        private void btnDelItem_Click(object sender, EventArgs e)
        {
            if (this.dtpData.RowCount <= 1)
                return;
            if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                dtpData.Rows.RemoveAt(dtpData.CurrentRow.Index);
                //EditStatus = Common.BillOperateType.Update;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

            //if (tMain.Rows[0]["assessor"] != null && tMain.Rows[0]["assessor"].ToString() == "已审批")
            if (this.txtStatus.Text == "已审批")
            {
                MessageBox.Show("无法删除已审批单据.");
                return;
            }

            if ((EditStatus != Common.BillOperateType.Add) & (EditStatus != Common.BillOperateType.Update))
                return;

            this.dtpData.CancelEdit();

            if (EditStatus == Common.BillOperateType.Add)
            {
                tMain.Rows.Clear();
                tDetail.Rows.Clear();
                return;
            }

            //(EditStatus == Common.BillOperateType.Update)
            int BillId = (int)tMain.Rows[0]["id"];

            if (MessageBox.Show("确认删除整张单吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (BaseDataProxy.DeleteRecvMaterial(BillId))
                {
                    
                    //dtpData.Rows.Clear();
                    for (int i = dtpData.Rows.Count - 2; i >= 0; i--)
                    {
                        dtpData.Rows.RemoveAt(i);
                    }
                    SetControlsStatus(true);
                    MessageBox.Show("已成功删除单据.");
                }
                else
                    MessageBox.Show("无法删除单据.");
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dtpOutDate_ValueChanged(object sender, EventArgs e)
        {
            if (tMain.Rows.Count > 0)
                tMain.Rows[0]["recvDate"] = this.dtpOutDate.Value;
        }

        private void cbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tMain.Rows.Count > 0)
                tMain.Rows[0]["type"] = this.cbType.Text;
        }

        private void dtpData_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void dtpData_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            int irow = e.RowIndex;
            int icol = e.ColumnIndex;
            if (irow < 0 || icol < 0)
            {
                return;
            }
            else if (dtpData.Columns[icol].Name == "t_depot")
            {
                int a = this.dtpData.RCText(irow, "t_depot").IndexOf('[');
                int b = this.dtpData.RCText(irow, "t_depot").IndexOf(']');
                int c = 0;

                if (a > 0 && b > a)
                {
                    c = Convert.ToInt32(this.dtpData.RCText(irow, "t_depot").Substring(a + 1, b - a - 1));
                    this.dtpData.Rows[irow].Cells["id3"].Value = c;
                }

                if (!bGraph)
                {
                    bGraph = true;
                    if (MessageBox.Show("以下是否设为相同？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        for (int i = dtpData.Rows.Count - 2; irow < i; i--)
                        {
                            dtpData.Rows[i].Cells["t_depot"].Value = dtpData.RCText(irow, icol);
                            this.dtpData.Rows[i].Cells["id3"].Value = c;
                        }
                    }
                    else
                    {
                        bGraph = false;
                        return;
                    }
                    bGraph = false;
                }   

            }
        }

        private void btnFromSc_Click(object sender, EventArgs e)
        {
            this.cbType.Text = "生产领料";
            SelectScdFrm dlg = new SelectScdFrm();
            dlg.ShowDialog();
            this.cbType.Enabled = false;
        }

        private void dtpData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //this.dtpData.Rows[e.RowIndex].HeaderCell.Value = Convert.ToString(e.RowIndex + 1);//显示行号，也可以设置成显示其他信息 
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {

        }

        private void btnConfirmOK_Click(object sender, EventArgs e)
        {
            tMain.Rows[0]["accessor"] = SysLoginUserInfo.UserId;
            tMain.Rows[0]["verifyTime"] = DateTime.Now;
            tMain.AcceptChanges();

            int BillId = (int)tMain.Rows[0]["id"];

            VerifyBillResult ver = BaseDataProxy.VerifyBill("LL", BillId, SysLoginUserInfo.UserId, true);

            if (ver.Pass)
            {
                this.txtStatus.Text = "已批";
                this.txtAccessor.Text = SysLoginUserInfo.UserName;
            }
            else
            {
                this.txtStatus.Text = "";
                this.txtAccessor.Text = "";
            }
            MessageBox.Show(ver.Message);
        }

        private void btnConfirmNo_Click(object sender, EventArgs e)
        {
            if (tMain.Rows.Count <= 0 || dtpData.Rows.Count <= 1)
                return;
            tMain.Rows[0]["accessor"] = DBNull.Value;
            tMain.Rows[0]["verifyTime"] = DBNull.Value;
            tMain.Rows[0]["status"] = "未批";
            tMain.AcceptChanges();

            int BillId = (int)tMain.Rows[0]["id"];

            VerifyBillResult ver = BaseDataProxy.VerifyBill("LL", BillId, SysLoginUserInfo.UserId, false);

            if (ver.Pass)
            {
                this.txtStatus.Text = "未批";
                this.txtAccessor.Text = "";
                SetControlsStatus(true);
                EditStatus = Common.BillOperateType.Update;
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = true;
 
            }
            else
            {

            }
            MessageBox.Show(ver.Message);
        }

        private void dtpData_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.dtpData);
        }

        private void dtpData_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            Common.ShowDataGridViewRowNo(this.dtpData);
        }

        TextBox control = null;

        private void dtpData_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.dtpData.Columns[this.dtpData.CurrentCell.ColumnIndex].Name == "t_depot")
                return;
            e.CellStyle.BackColor = Color.AliceBlue;//设置编译时的颜色
            control = (TextBox)e.Control;
            switch (this.dtpData.CurrentCell.ColumnIndex)
            {
                //case 6:
                //    control.Leave += new EventHandler(control_Leave);
                //    break;
                case 6:
                    control.KeyPress += new KeyPressEventHandler(control_KeyPress);
                    break;
            }
        }

        /// <summary>
        /// 单元格输入框编辑内容按键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void control_KeyPress(object sender, KeyPressEventArgs e)
        {
            ////限制只能输入0-9的数字，退格键，小数点
            if (this.dtpData.CurrentCell.ColumnIndex == 6)
            {
                if (((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57) || e.KeyChar == 8 || e.KeyChar == 46)
                { }
                else
                    e.Handled = true;
            }
        }

        /// <summary>
        /// 单元格编辑离开时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void control_Leave(object sender, EventArgs e)
        {
            //如果需要限制字符串输入长度
            if (control.Text.Length >= 3)
            {
                control.Focus();
            }
        }
    }
}
